<template>
  <div class="task-history">
    <h1 class="page-title">历史任务记录</h1>
    
    <p class="page-description">
      📝 查看所有已完成的任务记录，回顾孩子的成长足迹
    </p>

    <!-- 筛选条件 -->
    <el-card class="content-card filter-card" shadow="hover">
      <el-form :inline="true">
        <el-form-item label="快捷选择">
          <el-select v-model="quickSelect" @change="handleQuickSelect" placeholder="选择时间范围" style="width: 150px">
            <el-option label="近1周" value="1week" />
            <el-option label="近1个月" value="1month" />
            <el-option label="近3个月" value="3months" />
            <el-option label="近半年" value="6months" />
            <el-option label="近1年" value="1year" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            style="width: 260px"
          />
        </el-form-item>
        
        <el-form-item label="完成状态">
          <el-select v-model="statusFilter" @change="filterRecords" style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="已完成" value="1" />
            <el-option label="未完成" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="完成度筛选">
          <el-select v-model="scoreFilter" @change="filterRecords" style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="优秀(≥90分)" value="90" />
            <el-option label="良好(≥80分)" value="80" />
            <el-option label="及格(≥60分)" value="60" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 历史任务记录列表 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>任务记录</span>
          <span class="record-count">
            共 {{ filteredList.length }} 条记录
            <span v-if="statusFilter || scoreFilter" class="filter-tip">（已筛选）</span>
          </span>
        </div>
      </template>

      <div v-loading="loading" class="history-container">
        <el-empty v-if="filteredList.length === 0" description="暂无符合条件的记录" />

        <el-timeline v-else>
          <el-timeline-item
            v-for="record in filteredList"
            :key="record.id"
            :timestamp="formatDateTime(record.loggedAt)"
            placement="top"
          >
            <el-card class="history-card">
              <div class="history-header">
                <div class="history-title">
                  <h3>{{ record.taskTitle || `任务 #${record.taskId}` }}</h3>
                  <el-tag :type="record.status ? 'success' : 'info'" size="small">
                    {{ record.status ? '已完成' : '未完成' }}
                  </el-tag>
                </div>
                <div class="history-score">
                  <span class="score-label">完成度</span>
                  <span class="score-value">{{ record.score || 0 }}</span>
                  <span class="score-unit">分</span>
                </div>
              </div>

              <div v-if="record.taskDescription" class="history-description">
                <el-icon><InfoFilled /></el-icon>
                <span>{{ record.taskDescription }}</span>
              </div>

              <div v-if="record.remarks" class="history-remarks">
                <el-icon><Document /></el-icon>
                <span>{{ record.remarks }}</span>
              </div>

              <div v-if="record.photosCount > 0" class="history-photos">
                <el-icon><Picture /></el-icon>
                <span>包含 {{ record.photosCount }} 张训练照片</span>
              </div>

              <!-- 操作按钮 -->
              <div v-if="record.status && record.score >= 80" class="history-actions">
                <el-button
                  type="primary"
                  size="small"
                  :icon="record.inGrowthBox ? 'Check' : 'Box'"
                  :disabled="record.inGrowthBox"
                  @click="handleAddToGrowthBox(record)"
                >
                  {{ record.inGrowthBox ? '已在成长盒' : '加入成长盒' }}
                </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getProgressHistory } from '@/api/progress'
import { addTaskToGrowthBox } from '@/api/growthBox'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const userStore = useUserStore()

const loading = ref(false)
const quickSelect = ref('1month')
const dateRange = ref([])
const statusFilter = ref('')
const scoreFilter = ref('')
const historyList = ref([])

const formatDateTime = (dateTime) => {
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
}

// 快捷选择处理
const handleQuickSelect = (value) => {
  const endDate = dayjs()
  let startDate
  
  switch (value) {
    case '1week':
      startDate = endDate.subtract(1, 'week')
      break
    case '1month':
      startDate = endDate.subtract(1, 'month')
      break
    case '3months':
      startDate = endDate.subtract(3, 'month')
      break
    case '6months':
      startDate = endDate.subtract(6, 'month')
      break
    case '1year':
      startDate = endDate.subtract(1, 'year')
      break
    default:
      startDate = endDate.subtract(1, 'week')
  }
  
  dateRange.value = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
  loadHistory()
}

// 自定义日期范围变化处理
const handleDateChange = () => {
  quickSelect.value = '' // 清空快捷选择
  loadHistory()
}

// 筛选后的列表
const filteredList = computed(() => {
  let list = historyList.value

  // 按状态筛选
  if (statusFilter.value !== '') {
    list = list.filter(record => record.status === parseInt(statusFilter.value))
  }

  // 按分数筛选
  if (scoreFilter.value !== '') {
    const minScore = parseInt(scoreFilter.value)
    list = list.filter(record => (record.score || 0) >= minScore)
  }

  return list
})

// 加载历史记录
const loadHistory = async () => {
  loading.value = true
  try {
    const userId = userStore.userInfo?.userId
    if (!userId || !dateRange.value || dateRange.value.length !== 2) return

    const params = {
      userId,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }

    const data = await getProgressHistory(params)
    // 为每条记录添加inGrowthBox标识
    historyList.value = (data || []).map(record => ({
      ...record,
      inGrowthBox: false
    }))
  } catch (error) {
    console.error('加载历史记录失败:', error)
    ElMessage.error('加载历史记录失败')
  } finally {
    loading.value = false
  }
}

// 筛选记录（不需要重新加载，只是过滤）
const filterRecords = () => {
  // computed会自动更新
}

// 添加任务到成长盒
const handleAddToGrowthBox = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要将"${record.taskTitle}"加入成长盒吗？这将作为孩子成长的重要印记。`,
      '加入成长盒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    await addTaskToGrowthBox({
      taskId: record.taskId,
      note: record.remarks || `完成度：${record.score}分`
    })

    // 标记为已在成长盒中
    record.inGrowthBox = true

    ElMessage.success('已成功加入成长盒！这是孩子成长的印记 ✨')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('加入成长盒失败:', error)
      ElMessage.error(error.message || '加入成长盒失败')
    }
  }
}

onMounted(() => {
  // 初始化默认为近1个月
  handleQuickSelect('1month')
})
</script>

<style scoped>
.task-history {
  padding: 20px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.content-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.filter-card {
  background: linear-gradient(135deg, #fff5fb 0%, #fff9f5 100%);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.record-count {
  color: #909399;
  font-size: 14px;
  font-weight: normal;
}

.filter-tip {
  color: #409eff;
  font-size: 12px;
}

.history-container {
  max-height: 800px;
  overflow-y: auto;
  padding: 20px 0;
}

.history-card {
  margin-top: 10px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.history-title {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.history-title h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.history-score {
  display: flex;
  align-items: baseline;
  gap: 5px;
  padding: 8px 15px;
  background: linear-gradient(135deg, #fff5fb 0%, #fff9f5 100%);
  border-radius: 8px;
}

.score-label {
  font-size: 12px;
  color: #909399;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  color: #ffb3d9;
}

.score-unit {
  font-size: 12px;
  color: #909399;
}

.history-description,
.history-remarks,
.history-photos {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  margin-top: 10px;
  background: #f9f9f9;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
}

.history-description {
  color: #909399;
  background: #f5f7fa;
  font-size: 13px;
}

.history-photos {
  color: #409eff;
  background: #ecf5ff;
}

.history-actions {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 13px;
}

@media (max-width: 768px) {
  .task-history {
    padding: 15px;
  }

  .history-header {
    flex-direction: column;
    gap: 15px;
  }

  .history-score {
    width: 100%;
    justify-content: center;
  }

  .filter-card :deep(.el-form) {
    display: flex;
    flex-direction: column;
  }

  .filter-card :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}
</style>
